<template>
  <div class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="120px"
      style="width: 800px; margin-left:50px;">
      <el-form-item :label="$t('积分兑换名称')" prop="name">
        <el-input v-model="dataForm.name" :required="true" />
      </el-form-item>

      <el-form-item :label="$t('积分需求')" prop="point">
        <el-input v-model.number="dataForm.point" :min="0" :required="true" />
      </el-form-item>

      <el-form-item :label="$t('可兑换金额范围')" prop="minMoney">
        <el-input style="width:300px" v-model="dataForm.minMoney" type="number" :min="0"
          oninput="if(value.indexOf('.') != -1) {value= value.slice(0,value.indexOf('.')+3)}" />
        -
        <el-input style="width:300px" v-model="dataForm.maxMoney" type="number" :min="dataForm.minMoney != null ? dataForm.minMoney : 0"
          oninput="if(value.indexOf('.') != -1) {value= value.slice(0,value.indexOf('.')+3)}" />
        $
      </el-form-item>

      <!-- 级联单选/多选分类 -->
      <el-form-item :label="$t('商品分类')" required class="category-inline">
        <!-- 一级分类（单选） -->
        <el-select
          v-model="selectedLevel1"
          prop="selectedLevel1"
          placeholder="一级分类"
          @change="handleLevel1Change"
          clearable>
          <el-option v-for="item in level1Options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id" />
        </el-select>

        <!-- 二级分类（单选） -->
        <el-select
          v-model="selectedLevel2"
          prop="selectedLevel2"
          placeholder="二级分类"
          @change="handleLevel2Change"
          clearable>
          <el-option v-for="item in level2Options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id" />
        </el-select>

        <!-- 三级分类（多选） -->
        <el-select style="width:200px"
          v-model="selectedLevel3"
          prop="selectedLevel3"
          multiple
          collapse-tags
          placeholder="三级分类（可多选）"
          clearable>
          <el-option v-for="item in level3Options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id" />
        </el-select>
      </el-form-item>

    </el-form>
    <div class="op-container">
      <el-button @click="handleBack" style="margin-right: 480px">{{ $t('Back') }}</el-button>
      <el-button v-if="dialogStatus == 'create'" v-permission="['GET /admin/p/point_exchange_add']" type="primary"
        @click="createData">{{ $t('Confirm') }}
      </el-button>
      <el-button v-if="this.status == true" v-permission="['GET /admin/p/point_exchange_add']" type="primary"
        @click="updateData">{{ $t('Confirm') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { uploadPath } from '../../api/storage'
import { addPointExchange, updatePointExchange } from '../../api/exchange'
import { listLevel1Categories, listLevel2Categories, listLevel3Categories } from '../../api/category'
import { getToken } from '../../utils/auth'

export default {
  name: 'pointExchangeAdd',
  data() {
    // 表单金额范围校验函数，确保金额范围不为空且最小值不大于最大值
    const validateMoneyRange = (rule, value, callback) => {
      let flag = false;
      if ((this.dataForm.minMoney == undefined || this.dataForm.minMoney == '')
        && (this.dataForm.maxMoney == undefined || this.dataForm.maxMoney == '')) {
        flag = true;
      }
      if ((this.dataForm.minMoney - this.dataForm.maxMoney)>0) {
        flag = true;
      }
      if (flag) {
        return callback(new Error('金额不能同时为空或者最小值大于最大值'));
      } else {
        callback()
      }
    }

    // 商品分类校验函数，确保商品分类不为空
    const validateCategoryId = (rule, value, callback) => {
      if (this.dataForm.categoryId == undefined || this.dataForm.categoryId == '') {
        return callback(new Error('商品分类不能为空'));
      } else {
        callback()
      }
    }

    return {
      uploadPath, // 上传路径
      dataForm: {
        id: undefined, // 数据ID
        name: undefined, // 积分兑换名称
        point: undefined, // 积分需求
        minMoney: 0, // 最小可兑换金额
        maxMoney: 0, // 最大可兑换金额
        categoryIds: [], // 三级分类ID数组
        flag: undefined // 标志位，状态标识
      },
      status: undefined, // 当前状态标识
      dialogStatus: '', // 弹窗状态（创建或更新）
      rules: {
        name: [
          { required: true, message: this.$t('积分兑换名称不能为空'), trigger: 'blur' }
        ],
        point: [
          { required: true, message: this.$t('积分需求不能为空'), trigger: 'blur' }
        ],
        minMoney: [
          { validator: validateMoneyRange, required: true, trigger: 'blur' }
        ],
        maxMoney: [
          { validator: validateMoneyRange, required: true, trigger: 'blur' }
        ],
        categoryId: [
          { validator: validateCategoryId, required: true, trigger: 'blur' }
        ],
        selectedLevel1: [
          { required: true, message: '一级分类不能为空', trigger: 'change' }
        ],
        selectedLevel2: [
          { required: true, message: '二级分类不能为空', trigger: 'change' }
        ],
        selectedLevel3: [
          { type: 'array', required: true, message: '三级分类不能为空', trigger: 'change' }
        ],
      },
      level1Options: [], // 一级分类选项列表
      level2Options: [], // 二级分类选项列表
      level3Options: [], // 三级分类选项列表
      selectedLevel1: null, // 选中的一级分类ID
      selectedLevel2: null, // 选中的二级分类ID
      selectedLevel3: [] // 选中的三级分类ID数组（多选）
    }
  },
  beforeRouteLeave(to, form, next) {
    if ((this.dataForm.name || this.dataForm.point)) {
      this.$confirm(this.$t('离开当前页面数据将无法保存'), this.$t('提示'), {
        iconClass: "el-icon-question",//自定义图标样式
        confirmButtonText: this.$t("离开"),//确认按钮文字更换
        cancelButtonText: this.$t('留下'),//取消按钮文字更换
        showClose: true,//是否显示右上角关闭按钮
        type: "warning",//提示类型  success/info/warning/error
      }).then(function () {
        next();
        //确认操作
      }).then((data) => {
        //取消操作
      })
        .catch(function (err) {
          //捕获异常
        });
    } else {
      next();
    }
  },
  async created() {
    await this.init()
    this.loadLevel1Categories()
  },
  methods: {
    // 格式化状态码为对应的状态文本
    formatStatus(status) {
      if (status === 0) {
        return this.$t('新增')
      } else if (status === 1) {
        return this.$t('已上架')
      } else {
        return this.$t('已下架')
      }
    },
    // 初始化数据，根据路由参数设置表单状态及联动分类默认值
    async init() {
      if (this.$route.query.dialogStatus == 'update') {
        this.dataForm = this.$route.query.dataForm
        this.dataForm.flag = true
      }
      this.dialogStatus = this.$route.query.dialogStatus

      if (this.$route.query.dataForm != undefined) {
        if (this.$route.query.dataForm.status == 2) {
          this.status = true
        } else {
          this.status = false
        }
      }
      // 加载联动反显（编辑时）
      if (this.dataForm.id) {
        this.selectedLevel1 = this.dataForm.selectedLevel1
        // 等待加载二级分类列表
        await this.handleLevel1Change(this.selectedLevel1)
        this.selectedLevel2 = this.dataForm.selectedLevel2
        // 等待加载三级分类列表
        await this.handleLevel2Change(this.selectedLevel2)
        this.selectedLevel3 = [...this.dataForm.categoryIds]
      }
    },
    // 返回上一页操作
    handleBack() {
      this.$router.push({ path: '/exchange/list' })
    },
    // 创建积分兑换数据，提交表单并处理响应
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.categoryIds = this.selectedLevel3
          this.dataForm.selectedLevel1 = this.selectedLevel1
          this.dataForm.selectedLevel2 = this.selectedLevel2

          addPointExchange(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('积分兑换创建成功')
              })
              this.dataForm.name=''
              this.dataForm.point=''
              this.$router.push({ path: '/exchange/list' })
            }).catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
          this.resetForm()
        }
      })
    },
    // 更新积分兑换数据，提交表单并处理响应
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.categoryIds = this.selectedLevel3
          this.dataForm.selectedLevel1 = this.selectedLevel1
          this.dataForm.selectedLevel2 = this.selectedLevel2
          updatePointExchange(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('积分兑换编辑成功')
              })
              this.$router.push({ path: '/exchange/list' })
            }).catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
    // 加载一级分类选项列表
    loadLevel1Categories() {
      listLevel1Categories().then(response => {
        this.level1Options = response.data.data || []
      })
    },
    // 处理一级分类变更，重置并加载对应二级分类选项
    handleLevel1Change(value) {
      this.selectedLevel2 = null
      this.selectedLevel3 = []
      this.level2Options = []
      this.level3Options = []
      if (value) {
        return listLevel2Categories(value).then(response => {
          this.level2Options = response.data.data || []
        })
      } else {
        return Promise.resolve()
      }
    },
    // 处理二级分类变更，重置并加载对应三级分类选项
    handleLevel2Change(value) {
      this.selectedLevel3 = []
      this.level3Options = []
      if (value) {
        return listLevel3Categories(value).then(response => {
          this.level3Options = response.data.data || []
        })
      } else {
        return Promise.resolve()
      }
    },
    // 重置表单数据
    resetForm() {
      this.dataForm = {}
    }
  },
  computed: {
    // 请求头部信息，包含认证Token
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  }
}
</script>

<style scoped>
.category-inline .el-form-item__content {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}

.category-inline .el-select {
  width: 140px;
  margin-right: 12px;
}
</style>
